package com.trailwalker.mediaplayer.service.data;

import com.alibaba.fastjson.JSON;
import com.trailwalker.JavaUtils.log.LogUtils;
import com.trailwalker.mediaplayer.dao.DatabaseUtils;
import com.trailwalker.mediaplayer.service.entity.MediaInfo;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Trailwalker
 * @create 2021-09-03 13:49
 * @des
 */
public class MediaPlayerDataService {

    private static final String TAG = MediaPlayerDataService.class.getSimpleName();

    private DatabaseUtils databaseUtils;

    public MediaPlayerDataService() {
        databaseUtils = new DatabaseUtils("jdbc:h2:~/MediaPlayerDb");
    }

    public void createTable() {
        createMediaInfoTableSql();
    }

    public void createMediaInfoTableSql() {
        String createMediaInfoTableSql = "CREATE TABLE IF NOT EXISTS `MediaInfo`(" +
                "`id` INT UNSIGNED AUTO_INCREMENT," +
                "`name` VARCHAR(100)," +
                "`totalTime` DOUBLE," +
                "`url` VARCHAR(100)," +
                "PRIMARY KEY (`id`)" +
                ");";
        databaseUtils.createTable(createMediaInfoTableSql);
    }

    public void insertMediaInfo(MediaInfo mediaInfo) {
        String insertMediaInfoSql = "insert into MediaInfo values (null,'" + mediaInfo.getName() + "'," + mediaInfo.getTotalTime() + ",'" + mediaInfo.getUrl() + "')";
        int count = databaseUtils.insert(insertMediaInfoSql);
        if (count > 0) {
            LogUtils.log(TAG, "插入 " + JSON.toJSONString(mediaInfo) + " 成功");
        } else {
            LogUtils.log(TAG, "插入 " + JSON.toJSONString(mediaInfo) + " 失败");
        }
    }

    public List<MediaInfo> getMediaInfoList() {
        List<MediaInfo> mediaInfoList = new ArrayList<>();
        String queryMediaInfoSql = "select * from MediaInfo;";
        ResultSet resultSet = databaseUtils.query(queryMediaInfoSql);
        try {
            while (resultSet.next()) {
                MediaInfo mediaInfo = new MediaInfo();
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                double totalTime = resultSet.getDouble("totalTime");
                String url = resultSet.getString("url");
                mediaInfo.setId(id);
                mediaInfo.setName(name);
                mediaInfo.setTotalTime(totalTime);
                mediaInfo.setUrl(url);
                mediaInfoList.add(mediaInfo);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return mediaInfoList;
    }

    public void release() {
        databaseUtils.release();
    }
}
